#ifndef __APP_IIC_HEADER__
#define __APP_IIC_HEADER__

#include <pinmux.h>
#include <ulog/ulog.h>
#include <aos/hal/i2c.h>

static i2c_dev_t i2cDevice;

static void InitializeSensor() {
    int32_t retVal = 0;
    retVal |= drv_pinmux_config(PA1, PA1_IIC_SCL);
    retVal |= drv_pinmux_config(PA4, PA4_IIC_SDA);
    // Initialize Pin Mux
    if (retVal != 0) {
        LOGE("IIC Driver", "Can't Configure Pin Mux, Error Code: %d", retVal);
        return;
    }
    i2cDevice.port = 0;
    i2cDevice.config.dev_addr = 0x40;
    i2cDevice.config.mode = I2C_MODE_MASTER;
    i2cDevice.config.freq = I2C_BUS_BIT_RATES_100K;
    i2cDevice.config.address_width = I2C_HAL_ADDRESS_WIDTH_7BIT;
    retVal |= hal_i2c_init(&i2cDevice);
    // Initialize I2C Controller
    if (retVal != 0) {
        LOGE("IIC Driver", "Can't Initialize IIC Controller, Error Code: %d", retVal);
        return;
    }
    uint8_t data[] = {0x00, 0x80};
    retVal |= hal_i2c_mem_write(&i2cDevice, 0x40, 0x02, I2C_MEM_ADDR_SIZE_8BIT, data, sizeof(data), HAL_WAIT_FOREVER);
    // Reset Sensor
    if (retVal != 0) {
        LOGE("IIC Driver", "Can't Send Reset To Sensor Via IIC, Error Code: %d", retVal);
        return;
    }
    data[1] = 0x00;
    retVal |= hal_i2c_mem_write(&i2cDevice, 0x40, 0x02, I2C_MEM_ADDR_SIZE_8BIT, data, sizeof(data), HAL_WAIT_FOREVER);
    // Write Configuration Into Sensor
    if (retVal != 0) {
        LOGE("IIC Driver", "Can't Send Configuration To Sensor Via IIC, Error Code: %d", retVal);
        return;
    }
}

static float ReadSensorTemperature() {
    int32_t retVal = 0;
    uint16_t sensorRawData = 0;
    uint8_t sensorRawDataArray[2] = {0};
    retVal |= hal_i2c_mem_read(&i2cDevice, 0x40, 0x00, I2C_MEM_ADDR_SIZE_8BIT, sensorRawDataArray, sizeof(uint8_t) * 2, HAL_WAIT_FOREVER);
    if (retVal != 0) {
        LOGE("IIC Driver", "Can't Read Temperature Data From Sensor, Error Code: %d", retVal);
        return -1.00;
    }
    sensorRawData = (sensorRawDataArray[0] << 8) + sensorRawDataArray[1];
    LOGD("IIC Driver", "Temperature Raw Data: %d.\n", sensorRawData);
    return (165 * sensorRawData) / 65535.0 - 40.0;
}

static float ReadSensorHumidity() {
    int32_t retVal = 0;
    uint16_t sensorRawData = 0;
    uint8_t sensorRawDataArray[2] = {0};
    retVal |= hal_i2c_mem_read(&i2cDevice, 0x40, 0x01, I2C_MEM_ADDR_SIZE_8BIT, sensorRawDataArray, sizeof(uint8_t) * 2, HAL_WAIT_FOREVER);
    if (retVal != 0) {
        LOGE("IIC Driver", "Can't Read Humidity Data From Sensor, Error Code: %d", retVal);
        return -1.00;
    }
    sensorRawData = (sensorRawDataArray[0] << 8) + sensorRawDataArray[1];
    LOGD("IIC Driver", "Humidity Raw Data: %d.\n", sensorRawData);
    return sensorRawData / 65535.0;
}

#endif